using System;
using System.Collections;
using System.Data;
using MySql.Data.MySqlClient;

namespace WIT.DAQ.Core.Helper;

/// <summary>
/// MySql帮助类
/// </summary>
internal class MySQLHelper
{
	private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

	/// <summary>
	///  给定连接的数据库用假设参数执行一个sql命令（不返回数据集）
	/// </summary>
	/// <param name="connectionString">一个有效的连接字符串</param>
	/// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
	/// <param name="cmdText">存储过程名称或者sql命令语句</param>
	/// <param name="commandParameters">执行命令所用参数的集合</param>
	/// <returns>执行命令所影响的行数</returns>
	internal static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
	{
		MySqlCommand mySqlCommand = new MySqlCommand();
		using MySqlConnection conn = new MySqlConnection(connectionString);
		PrepareCommand(mySqlCommand, conn, null, cmdType, cmdText, commandParameters);
		int result = mySqlCommand.ExecuteNonQuery();
		mySqlCommand.Parameters.Clear();
		return result;
	}

	/// <summary>
	/// 用现有的数据库连接执行一个sql命令（不返回数据集）
	/// </summary>
	/// <param name="connection">一个现有的数据库连接</param>
	/// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
	/// <param name="cmdText">存储过程名称或者sql命令语句</param>
	/// <param name="commandParameters">执行命令所用参数的集合</param>
	/// <returns>执行命令所影响的行数</returns>
	internal static int ExecuteNonQuery(MySqlConnection connection, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
	{
		MySqlCommand mySqlCommand = new MySqlCommand();
		PrepareCommand(mySqlCommand, connection, null, cmdType, cmdText, commandParameters);
		int result = mySqlCommand.ExecuteNonQuery();
		mySqlCommand.Parameters.Clear();
		return result;
	}

	/// <summary>
	///             使用现有的SQL事务执行一个sql命令（不返回数据集）
	/// </summary>
	/// <remarks>
	///             举例:
	///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
	/// </remarks>
	/// <param name="trans">一个现有的事务</param>
	/// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
	/// <param name="cmdText">存储过程名称或者sql命令语句</param>
	/// <param name="commandParameters">执行命令所用参数的集合</param>
	/// <returns>执行命令所影响的行数</returns>
	internal static int ExecuteNonQuery(MySqlTransaction trans, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
	{
		MySqlCommand mySqlCommand = new MySqlCommand();
		PrepareCommand(mySqlCommand, trans.Connection, trans, cmdType, cmdText, commandParameters);
		int result = mySqlCommand.ExecuteNonQuery();
		mySqlCommand.Parameters.Clear();
		return result;
	}

	/// <summary>
	/// 用执行的数据库连接执行一个返回数据集的sql命令
	/// </summary>
	/// <remarks>
	/// 举例:
	///  MySqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
	/// </remarks>
	/// <param name="connectionString">一个有效的连接字符串</param>
	/// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
	/// <param name="cmdText">存储过程名称或者sql命令语句</param>
	/// <param name="commandParameters">执行命令所用参数的集合</param>
	/// <returns>包含结果的读取器</returns>
	internal static MySqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
	{
		MySqlCommand mySqlCommand = new MySqlCommand();
		MySqlConnection mySqlConnection = new MySqlConnection(connectionString);
		try
		{
			PrepareCommand(mySqlCommand, mySqlConnection, null, cmdType, cmdText, commandParameters);
			MySqlDataReader result = mySqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
			mySqlCommand.Parameters.Clear();
			return result;
		}
		catch
		{
			mySqlConnection.Close();
			throw;
		}
	}

	/// <summary>
	/// 返回DataSet
	/// </summary>
	/// <param name="connectionString">一个有效的连接字符串</param>
	/// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
	/// <param name="cmdText">存储过程名称或者sql命令语句</param>
	/// <param name="commandParameters">执行命令所用参数的集合</param>
	/// <returns></returns>
	internal static DataSet ExecuteDataset(string connectionString, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
	{
		MySqlCommand mySqlCommand = new MySqlCommand();
		MySqlConnection mySqlConnection = new MySqlConnection(connectionString);
		try
		{
			PrepareCommand(mySqlCommand, mySqlConnection, null, cmdType, cmdText, commandParameters);
			MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter();
			mySqlDataAdapter.SelectCommand = mySqlCommand;
			DataSet dataSet = new DataSet();
			mySqlDataAdapter.Fill(dataSet);
			mySqlCommand.Parameters.Clear();
			mySqlConnection.Close();
			return dataSet;
		}
		catch (Exception ex)
		{
			throw ex;
		}
	}

	/// <summary>
	/// 使用现有的SQL事务执行一个sql命令（返回DataSet）
	/// </summary>
	/// <param name="trans">一个现有的事务</param>
	/// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
	/// <param name="cmdText">存储过程名称或者sql命令语句</param>
	/// <param name="commandParameters">执行命令所用参数的集合</param>
	/// <returns></returns>
	internal static DataSet ExecuteDataset(MySqlTransaction trans, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
	{
		MySqlCommand mySqlCommand = new MySqlCommand();
		try
		{
			PrepareCommand(mySqlCommand, trans.Connection, trans, cmdType, cmdText, commandParameters);
			MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter();
			mySqlDataAdapter.SelectCommand = mySqlCommand;
			DataSet dataSet = new DataSet();
			mySqlDataAdapter.Fill(dataSet);
			mySqlCommand.Parameters.Clear();
			return dataSet;
		}
		catch (Exception ex)
		{
			throw ex;
		}
	}

	/// <summary>
	/// 用指定的数据库连接字符串执行一个命令并返回一个数据集的第一列
	/// </summary>
	/// <remarks>
	///             例如:
	///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
	/// </remarks>
	///             <param name="connectionString">一个有效的连接字符串</param>
	/// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
	/// <param name="cmdText">存储过程名称或者sql命令语句</param>
	/// <param name="commandParameters">执行命令所用参数的集合</param>
	/// <returns>用 Convert.To{Type}把类型转换为想要的 </returns>
	internal static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
	{
		MySqlCommand mySqlCommand = new MySqlCommand();
		using MySqlConnection conn = new MySqlConnection(connectionString);
		PrepareCommand(mySqlCommand, conn, null, cmdType, cmdText, commandParameters);
		object result = mySqlCommand.ExecuteScalar();
		mySqlCommand.Parameters.Clear();
		return result;
	}

	/// <summary>
	/// 用指定的数据库连接执行一个命令并返回一个数据集的第一列
	/// </summary>
	/// <remarks>
	/// 例如:
	///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
	/// </remarks>
	/// <param name="connection">一个存在的数据库连接</param>
	/// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
	/// <param name="cmdText">存储过程名称或者sql命令语句</param>
	/// <param name="commandParameters">执行命令所用参数的集合</param>
	/// <returns>用 Convert.To{Type}把类型转换为想要的 </returns>
	internal static object ExecuteScalar(MySqlConnection connection, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
	{
		MySqlCommand mySqlCommand = new MySqlCommand();
		PrepareCommand(mySqlCommand, connection, null, cmdType, cmdText, commandParameters);
		object result = mySqlCommand.ExecuteScalar();
		mySqlCommand.Parameters.Clear();
		return result;
	}

	/// <summary>
	/// 使用现有的SQL事务执行一个sql命令并返回一个数据集的第一列
	/// </summary>
	/// <remarks>
	/// 例如:
	///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
	/// </remarks>
	/// <param name="trans">一个现有的事务</param>
	/// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
	/// <param name="cmdText">存储过程名称或者sql命令语句</param>
	/// <param name="commandParameters">执行命令所用参数的集合</param>
	/// <returns>用 Convert.To{Type}把类型转换为想要的 </returns>
	internal static object ExecuteScalar(MySqlTransaction trans, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
	{
		MySqlCommand mySqlCommand = new MySqlCommand();
		PrepareCommand(mySqlCommand, trans.Connection, trans, cmdType, cmdText, commandParameters);
		object result = mySqlCommand.ExecuteScalar();
		mySqlCommand.Parameters.Clear();
		return result;
	}

	/// <summary>
	/// 将参数集合添加到缓存
	/// </summary>
	/// <param name="cacheKey">添加到缓存的变量</param>
	/// <param name="commandParameters">一个将要添加到缓存的sql参数集合</param>
	internal static void CacheParameters(string cacheKey, params MySqlParameter[] commandParameters)
	{
		parmCache[cacheKey] = commandParameters;
	}

	/// <summary>
	/// 找回缓存参数集合
	/// </summary>
	/// <param name="cacheKey">用于找回参数的关键字</param>
	/// <returns>缓存的参数集合</returns>
	internal static MySqlParameter[] GetCachedParameters(string cacheKey)
	{
		MySqlParameter[] array = (MySqlParameter[])parmCache[cacheKey];
		if (array == null)
		{
			return null;
		}
		MySqlParameter[] array2 = new MySqlParameter[array.Length];
		int i = 0;
		for (int num = array.Length; i < num; i++)
		{
			array2[i] = (MySqlParameter)((ICloneable)array[i]).Clone();
		}
		return array2;
	}

	/// <summary>
	/// 准备执行一个命令
	/// </summary>
	/// <param name="cmd">sql命令</param>
	/// <param name="conn">OleDb连接</param>
	/// <param name="trans">OleDb事务</param>
	/// <param name="cmdType">命令类型例如 存储过程或者文本</param>
	/// <param name="cmdText">命令文本,例如:Select * from Products</param>
	/// <param name="cmdParms">执行命令的参数</param>
	private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, CommandType cmdType, string cmdText, MySqlParameter[] cmdParms)
	{
		if (conn.State != ConnectionState.Open)
		{
			conn.Open();
		}
		cmd.Connection = conn;
		cmd.CommandText = cmdText;
		if (trans != null)
		{
			cmd.Transaction = trans;
		}
		cmd.CommandType = cmdType;
		if (cmdParms != null)
		{
			foreach (MySqlParameter value in cmdParms)
			{
				cmd.Parameters.Add(value);
			}
		}
	}

	/// <summary>
	///
	/// </summary>
	/// <param name="connectionString"></param>
	/// <param name="cmdText"></param>
	/// <param name="page">page number(start with 1)</param>
	/// <param name="limit">qty per page</param>
	/// <param name="count">total qty</param>
	/// <param name="commandParameters"></param>
	/// <returns></returns>
	internal static DataSet QueryPageData(string connectionString, string cmdText, int page, int? limit, out int count, params MySqlParameter[] commandParameters)
	{
		if (page <= 0)
		{
			page = 1;
		}
		using MySqlConnection conn = new MySqlConnection(connectionString);
		try
		{
			MySqlCommand mySqlCommand = new MySqlCommand();
			string text = cmdText;
			cmdText = "SELECT COUNT(1) FROM (" + text + ") AS T;";
			PrepareCommand(mySqlCommand, conn, null, CommandType.Text, cmdText, commandParameters);
			object value = mySqlCommand.ExecuteScalar();
			mySqlCommand.Parameters.Clear();
			count = Convert.ToInt32(value);
			if (!limit.HasValue || limit <= 0)
			{
				cmdText = text;
			}
			else
			{
				if (count <= limit)
				{
					page = 1;
				}
				cmdText = $"{text} LIMIT {(page - 1) * limit},{limit}";
			}
			PrepareCommand(mySqlCommand, conn, null, CommandType.Text, cmdText, commandParameters);
			MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter();
			mySqlDataAdapter.SelectCommand = mySqlCommand;
			DataSet dataSet = new DataSet();
			mySqlDataAdapter.Fill(dataSet);
			mySqlCommand.Parameters.Clear();
			return dataSet;
		}
		catch (Exception ex)
		{
			throw ex;
		}
	}
}
